<template>
  <view class="new-or-edit-modal">
    <up-popup v-model:show="show" overlay mode="bottom" touchable maxHeight="'80%'" closeable closeOnClickOverlay
      @close="close" @open="open">
      <view class="modal-content">
        <view class="modal-header">
          <view class="modal-title">{{ title }}</view>
        </view>
        <up-form labelPosition="left" :model="formModel" :rules="rules" ref="formRef">
          <up-form-item labelWidth="100" label="处理状态" prop="status">
            <up-input disabled v-model="formModel.status" />
          </up-form-item>
          <up-form-item labelWidth="100" label="处理结果" prop="status">
            <up-radio-group v-model="formModel.resultId">
              <up-radio label="正常" name="1"></up-radio>
              <up-radio label="禁用" name="0"></up-radio>
            </up-radio-group>
          </up-form-item>
          <!-- uview-plus 上传图片 -->
          <up-form-item labelWidth="100" label="上传图片" prop="images">
            <view class="upload-container">
              <!-- 使用uni原生组件 -->
              <button class="upload-btn" @click="chooseImage">选择图片</button>
              
              <!-- 图片预览区域 -->
              <view class="image-preview" v-if="formModel.images && formModel.images.length > 0">
                <view class="image-item" v-for="(item, index) in formModel.images" :key="index">
                  <image :src="item.url" mode="aspectFill" class="preview-image" @click="previewImage(index)"></image>
                  <view class="delete-icon" @click="deletePic(index)">×</view>
                </view>
              </view>
            </view>
          </up-form-item>
          <up-form-item labelWidth="100" label="备注" prop="remark">
            <up-input v-model="formModel.remark" placeholder="请输入备注" />
          </up-form-item>
        </up-form>
      </view>

      <view class="modal-footer">
        <up-button type="primary" @click="submit">确认</up-button>
      </view>
    </up-popup>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue';
import { authorErrorOrder } from '@/api';

const formRef = ref(null);
const props = defineProps({
  type: {
    type: String,
    default: 'add',
  },
  rowData: {
    type: Object,
    default: () => { },
  }
})
defineOptions({ name: "OrderAbnormalModal" });
const emit = defineEmits(['success']);

// 创建响应式数据  
const show = defineModel<boolean>("show", { default: false });
const formModel = ref(createDefaultModel());
/**
 * 初始化表单数据
 * 处理状态
 * 处理结果单选框
 * 上传图片
 * 处理说明
 */
function createDefaultModel() {
  return {
    status: '',
    resultId: '',
    images: [],
    remark: '',
  };
}
const rules = reactive({
  resultId: [{ required: true, message: '请选择处理结果', trigger: 'blur' }],
  images: [{ 
    required: true, 
    message: '请上传图片', 
    trigger: 'change',
    validator: (rule, value, callback) => {
      if (!value || value.length === 0) {
        callback(new Error('请上传图片'));
      } else {
        callback();
      }
    }
  }],
  remark: [{ required: true, message: '请输入处理说明', trigger: 'blur' }],
})
function handleInitModel() {
  formModel.value = createDefaultModel();
  // 确保images数组被正确初始化
  if (!formModel.value.images) {
    formModel.value.images = [];
  }
  
  if (!props.rowData) return;
  if (props.type === "edit") {
    // 设置初始状态
    formModel.value.status = props.rowData.auditStatus === 0 ? '待处理' : '已处理';
    formModel.value.resultId = '1'; // 默认选择"正常"
    // 不再重置images数组，只确保它存在
    if (!formModel.value.images) {
      formModel.value.images = [];
    }
    console.log('初始化后的图片列表', formModel.value.images);
  }
}
const title = computed(() => {
  const titles: any = {
    add: "新增角色",
    edit: "处理异常",
  };
  return titles[props.type];
});


const submit = async () => {
  try {
    console.log('提交前的表单数据', formModel.value);
    await formRef.value.validate();
    
    // 检查是否有图片
    if (!formModel.value.images || formModel.value.images.length === 0) {
      uni.showToast({
        title: '请上传至少一张图片',
        icon: 'none'
      });
      return;
    }
    
    // 显示加载提示
    uni.showLoading({ title: '处理中...' });
    
    // 上传图片到服务器
    const uploadPromises = formModel.value.images.map(async (item) => {
      // 如果图片已经是网络地址，直接返回
      if (item.url.startsWith('http')) {
        return item.url;
      }
      
      // 否则上传到服务器
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: '/api/upload', // 替换为实际的上传接口
          filePath: item.url,
          name: 'file',
          success: (res) => {
            console.log('上传成功', res);
            try {
              // 解析返回的数据，获取图片URL
              const data = JSON.parse(res.data);
              resolve(data.url || item.url);
            } catch (e) {
              console.error('解析上传结果失败', e);
              resolve(item.url); // 解析失败时使用本地路径
            }
          },
          fail: (err) => {
            console.error('上传失败', err);
            reject(err);
          }
        });
      });
    });
    
    // 等待所有图片上传完成
    let uploadedUrls;
    try {
      uploadedUrls = await Promise.all(uploadPromises);
    } catch (error) {
      console.error('图片上传失败', error);
      uni.hideLoading();
      uni.showToast({
        title: '图片上传失败',
        icon: 'none'
      });
      return;
    }
    
    // 图片URL列表，保持为字符串数组
    console.log('图片URL列表', uploadedUrls);
    
    // 调用处理异常订单接口
    const result = await authorErrorOrder({
      bizCode: props.rowData.bizCode, // 审核ID
      dealResult: formModel.value.resultId === '1' ? 0 : 1, // 处理结果 0.正常 1.禁用
      dealRemark: formModel.value.remark, // 审核备注
      author: 0, // 审核状态 0.通过审核
      fileUrl: uploadedUrls // 图片URL数组
    });
    
    uni.hideLoading();
    
    if (result.success) {
      uni.showToast({
        title: '处理成功',
        icon: 'success'
      });
      
      // 关闭模态框
      close();
      
      // 通知父组件刷新列表
      emit('success');
    } else {
      uni.showToast({
        title: result.msg || '处理失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('处理异常订单失败', error);
    uni.showToast({
      title: '表单验证失败，请检查输入',
      icon: 'none'
    });
  }
}

// 定义方法  
function open() {
  show.value = true;
  handleInitModel();
  formRef.value.resetFields();
}

function close() {
  // 关闭逻辑，设置 show 为 false  
  show.value = false;
  console.log('close');
}

// 选择图片
const chooseImage = () => {
  // 确保images数组已初始化
  if (!formModel.value.images) {
    formModel.value.images = [];
  }
  
  uni.chooseImage({
    count: 9, // 最多可以选择的图片张数
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], // 从相册选择或使用相机拍摄
    success: (res) => {
      console.log('选择图片成功', res);
      
      // 将选择的图片添加到图片列表中
      res.tempFilePaths.forEach((path, index) => {
        formModel.value.images.push({
          url: path,
          type: 'image',
          name: `图片${formModel.value.images.length + index + 1}`,
          status: 'success'
        });
      });
      
      console.log('当前图片列表', formModel.value.images);
    },
    fail: (err) => {
      console.error('选择图片失败', err);
    }
  });
};

// 预览图片
const previewImage = (index) => {
  const urls = formModel.value.images.map(item => item.url);
  uni.previewImage({
    urls: urls,
    current: urls[index]
  });
};

// 删除图片
const deletePic = (index) => {
  formModel.value.images.splice(index, 1);
  console.log('删除后的图片列表', formModel.value.images);
}
</script>

<style scoped lang="scss">
.new-or-edit-modal {
  .modal-header {
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }

  .modal-content {
    padding: 20rpx;
  }
  
  .upload-container {
    width: 100%;
    
    .upload-btn {
      background-color: #f5f5f5;
      color: #666;
      font-size: 28rpx;
      padding: 15rpx 30rpx;
      border-radius: 8rpx;
      margin-bottom: 20rpx;
    }
    
    .image-preview {
      display: flex;
      flex-wrap: wrap;
      
      .image-item {
        position: relative;
        width: 160rpx;
        height: 160rpx;
        margin-right: 20rpx;
        margin-bottom: 20rpx;
        
        .preview-image {
          width: 100%;
          height: 100%;
          border-radius: 8rpx;
        }
        
        .delete-icon {
          position: absolute;
          top: -10rpx;
          right: -10rpx;
          width: 40rpx;
          height: 40rpx;
          background-color: rgba(0, 0, 0, 0.5);
          color: #fff;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 24rpx;
        }
      }
    }
  }
}
</style>
